<?php
namespace frontend\controllers;

use Yii;
use ReflectionClass;
use common\components\CrawlHelper;

class TestController extends BaseController
{
    public $layout = 'main_site';

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionCrawl()
    {
        return $this->render('crawl');
    }

    public function actionAjaxcrawl()
    {
        $returnCnt = '';
        try {
            $crawlHelper = new CrawlHelper();
            /**
            $filePath = "..\\console\\assets\\crawl\\tupian\\fengniao\\entry.json";
            $filePath = Yii::$app->helper->getCommonPath() . DIRECTORY_SEPARATOR . $filePath;
            $ruleCnt = file_get_contents($filePath);
             */
            $rule_txt = $_POST['ta_rule'];
            $returnData = $crawlHelper->loadTest(json_decode($rule_txt, true));
            if (!empty($returnData)) {
                $returnCnt = json_encode($returnData);
            }
        } catch(\Exception $e) {
        }
        echo $returnCnt;
    }

    public function actionRuntask()
    {
        set_time_limit(0);
        try {
            $taskAction = 'crawl/index';
            $actionArray = explode('/', $taskAction);
            $klassName = ucfirst($actionArray['0']) . 'Controller';
            $actionName = 'action' . ucfirst($actionArray['1']);

            $refClass = new ReflectionClass('console\\controllers\\' . $klassName);
            $refInstance = $refClass->newInstanceArgs(['crawl', Yii::$app]);
            $methodRunAction = $refClass->getmethod($actionName);
            $methodRunAction->invoke($refInstance);
        } catch(\Exception $e) {
            Yii::error("Crawl action exception:: {$e->getMessage()}");
        }
    }

}
